package com.dj.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dj.dormitory.commonutils.Result;
import com.dj.dormitory.entity.Bed;
import com.dj.dormitory.entity.DormitoryStudent;
import com.dj.dormitory.mapper.DormitoryStudentMapper;
import com.dj.dormitory.service.BedService;
import com.dj.dormitory.service.DormitoryStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DJ同学
 * @since 2021-01-24
 */
@Service
public class DormitoryStudentServiceImpl extends ServiceImpl<DormitoryStudentMapper, DormitoryStudent> implements DormitoryStudentService {
    @Autowired
    private BedService bedService;
    @Override
    public List<Map<String,Object>> getList(Integer dormitoryId) {
        List<Map<String,Object>> stus = this.baseMapper.getList(dormitoryId);
        return stus;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer selectDormitory(DormitoryStudent dormitoryStudent, Integer studentId) throws Exception {
        //查询是否选过床位
        QueryWrapper<DormitoryStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("student_id",studentId);
        List<DormitoryStudent> list = this.baseMapper.selectList(wrapper);
        Integer res = 0;
        if(list.size()!=0){
            res = 1;//选择过了
        }else{
            //出现bed是因为用到乐观锁 锁bed
            Bed bed = bedService.getById(dormitoryStudent.getBedId());
            dormitoryStudent.setStudentId(studentId);
            dormitoryStudent.setBuildingId(bed.getBuildingId());
            this.baseMapper.insert(dormitoryStudent);
            boolean b = bedService.updateById(bed);

            if(!b){
                res=2;//选择错误
                throw new Exception("选择床位错误");
            }
        }
        return res;
    }
}
